import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(
    title: '模拟初始创建的页面',
    home: Counter(),
  ));
}

///被const修饰的控件,不会进行重绘,所以不能引用为赋值变量的地方
//显示数字的部分
class CounterDisplay extends StatelessWidget {
  const CounterDisplay({Key? key, required this.count}) : super(key: key);

  final int count;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('按钮点击了$count次'),
    );
  }
}

class CounterIncrementor extends StatelessWidget {
  const CounterIncrementor({Key? key, required this.onPressed})
      : super(key: key);

  final VoidCallback onPressed; //点击事件的接口,可以通过他来传递点击事件

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: onPressed,
      child: const Icon(Icons.add),
    );
  }
}

///有状态的控件,也就是说可以进行重绘,被它包裹的无状态的控件,也可以跟着一起重绘
class Counter extends StatefulWidget {
  const Counter({Key? key}) : super(key: key);

  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _count = 0;

  //每当调用这个方法时,数字加1,并且进行重绘
  void _increment() {
    setState(() {
      _count += 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('数字增加的demo'),
      ),
      body: CounterDisplay(
        count: _count,
      ),
      floatingActionButton: CounterIncrementor(
        onPressed: _increment,
      ),
    );
  }
}
